import { Vector } from '../../engine/common/vector';
import { IWorld } from '../../engine/ecs/common/world.interface';
import { LocationComponent } from '../../engine/ecs/components/location.component';
import { System } from '../../engine/ecs/systems/system';
import { ShootEventComponent } from '../components/shoot-event.component';
import { player } from '../entities/player.entity';
import { BulletFactory } from '../factories/bullet-factory';

export class PlayerShootSystem extends System {
  #coolDown: number = 0.2;
  #elapsed: number = this.#coolDown;

  constructor(public bulletImage: HTMLImageElement) {
    super();
  }

  onUpdate(world: IWorld, dt: number) {
    const foundEntities = world.findEntitiesByComponent(ShootEventComponent);
    if (foundEntities.length === 0) {
      this.#elapsed += dt;
      return;
    }

    if (this.#elapsed >= this.#coolDown) {
      const locationComponent = world.findComponentByEntity(player, LocationComponent)!;

      BulletFactory.create(world, {
        location: locationComponent.location.add(new Vector(19, -15)),
        image: this.bulletImage,
        movementDirection: new Vector(0, -1),
        movementSpeed: 150,
      });

      this.#elapsed = 0;
    } else {
      this.#elapsed += dt;
    }
  }
}
